import axios from 'axios'
import {notification} from 'ant-design-vue';
import {useUserStore} from '@/stores/user';
import router from '@/router'

const {userInfo, clearUserInfo} = useUserStore()
export const serverUrl = import.meta.env.VITE_APP_BASE_URL

const service = axios.create({
    baseURL: serverUrl,
    timeout: 5000
})

// Add a request interceptor 全局请求拦截
service.interceptors.request.use(
    function (config) {
        // Do something before request is sent
        const token = userInfo.token
        if (token) {
            config.headers['token'] = token
        }
        // 此处还可以设置token
        return config
    },
    function (error) {
        // Do something with request error
        return Promise.reject(error)
    }
)

// Add a response interceptor 全局相应拦截
service.interceptors.response.use(
    function (response) {
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data

        // 如果是固定的数据返回模式，此处可以做继续完整的封装
        const resData = response.data || {}
        if (resData.success) {
            return resData
        }
        notification.error({description: resData.message});
        return Promise.reject(resData.message)
    },
    function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error

        // 此处需要对返回的状态码或者异常信息作统一处理
        console.log('error', error)
        const response = error.response;
        const status = response.status;
        if (status === 401) {
            // 判断状态码是401 跳转到登录页
            console.log("未登录或登录超时，跳到登录页");
            clearUserInfo()
            notification.error({description: "未登录或登录超时"});
            router.push('/login')
        }
        return Promise.reject(error)
    }
)

export const get = (url, params) => {
    return service.get(url, {
        params
    })
}

export const post = (url, data) => service.post(url, data)

export const put = (url, data) => service.put(url, data)

export const del = (url, data) => service.delete(url)